#include "pch.h"

#include "iosystem/xmlwriter.h"



namespace IO
{

	///
	RE_ImplementClass('XMLW', IO::XmlWriter, IO::StreamWriter);





	///
	XmlWriter::XmlWriter():
	m_xmlDoc(NULL),
		m_curNode(NULL)
	{

	}


	///
	XmlWriter::~XmlWriter()
	{
		if(this->IsOpen())
			this->Close();
	}





	///
	bool XmlWriter::Open()
	{
		if(StreamWriter::Open())
		{
			this->m_xmlDoc = r_new(ticpp::Document);

			this->m_xmlDoc->InsertEndChild(ticpp::Declaration("1.0", "UTF-8", ""));

			return true;
		}

		return false;
	}


	///
	void XmlWriter::Close()
	{
		// save stream here

		r_delete(this->m_xmlDoc);
		this->m_xmlDoc = 0;
		this->m_curNode = 0;

		StreamWriter::Close();
	}





	///
	bool XmlWriter::BeginNode(const Helper::String &node)
	{
		if(this->m_curNode == 0)
			this->m_curNode = this->m_xmlDoc->InsertEndChild(ticpp::Element(node.GetAsCharPtr()))->ToElement();
		else
			this->m_curNode = this->m_curNode->InsertEndChild(ticpp::Element(node.GetAsCharPtr()))->ToElement();

		return true;
	}


	///
	void XmlWriter::EndNode()
	{
		ticpp::Node * par = this->m_curNode->Parent();

		if(par == this->m_xmlDoc)
			this->m_curNode = 0;
		else
			this->m_curNode = par->ToElement();
	}


	///
	void XmlWriter::WriteContent(const Helper::String & text)
	{
		this->m_curNode->InsertEndChild(ticpp::Text(text.GetAsCharPtr()));
	}


	///
	void XmlWriter::WriteComment(const Helper::String &text)
	{
		ticpp::Comment comment;
		comment.SetValue(text.GetAsCharPtr());

		this->m_curNode->InsertEndChild(comment);
	}


	///
	void XmlWriter::SetString(const Helper::String & name, const Helper::String & val)
	{
		this->m_curNode->SetAttribute(name.GetAsCharPtr(), val.GetAsCharPtr());
	}


	///
	void XmlWriter::SetBool(const Helper::String &name, bool val)
	{
		Helper::String temp;
		temp.SetBool(val);

		this->SetString(name, temp);
	}


	///
	void XmlWriter::SetFloat(const Helper::String &name, float val)
	{
		Helper::String temp;
		temp.SetFloat(val);

		this->SetString(name, temp);
	}


	///
	void XmlWriter::SetFloat2(const Helper::String &name, const Math::float2 &val)
	{
		Helper::String temp;
		temp.SetFloat2(val);

		this->SetString(name, temp);
	}


	///
	void XmlWriter::SetFloat4(const Helper::String &name, const Math::float4 &val)
	{
		Helper::String temp;
		temp.SetFloat4(val);

		this->SetString(name, temp);
	}


	///
	void XmlWriter::SetInt(const Helper::String &name, int val)
	{
		Helper::String temp;
		temp.SetInt(val);

		this->SetString(name, temp);
	}


	///
	void XmlWriter::SetMatrix(const Helper::String &name, const Math::matrix &val)
	{
		Helper::String temp;
		temp.SetMatrix(val);

		this->SetString(name, temp);
	}

}